package com.nand.module.function.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.zxing.activity.CaptureActivity;
import com.nand.library.zxing.activity.CodeUtils;
import com.nand.module.function.R;
import com.nand.module.function.adapter.EquipmentAdapter;
import com.nand.module.function.adapter.MMMAdapter;
import com.nand.module.function.adapter.SearchAdapter;
import com.nand.module.function.bean.EqDatailBean;
import com.nand.module.function.bean.MMMBean;
import com.nand.module.function.constant.URL;
import com.nand.module.function.utils.LogUtils;
import com.nand.module.function.utils.SpacesItemDecoration;
import com.nand.module.function.view.CustomPartShadowPopupView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * created by 86185
 * on 2020/1/16
 */
@Route(path = "/function/mmm")
public class MMMActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mIvOrCode;
    private static final int REQUEST_CODE = 1001;
    private RecyclerView mRecycler;
    private MMMAdapter mAdapter;
    private HttpParams params;
    private SmartRefreshLayout swipeRefres;
    private int page;//加载页数
    private LinearLayout llEmpty;
    private List<MMMBean> mList = new ArrayList<>();
    private EditText mEtDjbh;
    private CheckBox cbType;
    private CheckBox cbSort;
    private int resultPosition = 0;//默认选择position
    private int typePosition = 0;//默认选择position
    private String[] resultData;//数据源
    private String[] typeData;//数据源
    private CustomPartShadowPopupView popupViewResult;
    private CustomPartShadowPopupView popupViewType;
    @Override
    protected int initLayout() {
        return R.layout.activity_mmm;
    }

    @Override
    protected boolean isActionBar() {
        return true;
    }


    @Override
    protected void initView() {
        mActionBar().setCenterText("物料移库看板");
        page = 1;
        mIvOrCode = findViewById(R.id.iv_or_code);
        mIvOrCode.setOnClickListener(this);
        mEtDjbh = findViewById(R.id.et_djbh);
        mRecycler = findViewById(R.id.recycler);
        cbType = findViewById(R.id.cb_result);
        cbSort = findViewById(R.id.cb_type);
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new MMMAdapter(R.layout.item_mmm);
        resultData = getResources().getStringArray(R.array.materials_type_list);
        typeData = getResources().getStringArray(R.array.materials_state_list);
        mRecycler.setAdapter(mAdapter);
        int space = 10;
        mRecycler.addItemDecoration(new SpacesItemDecoration(space));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String state = mList.get(position).getState();
                if ("待出库".equals(state)){
                    Intent intent2 = new Intent(MMMActivity.this, MMMDetailsActivity.class);
                    Bundle bundle2 = new Bundle();
                    bundle2.putInt("type", 1);
                    bundle2.putInt("oid", mList.get(position).getOid());
                    intent2.putExtras(bundle2);
                    startActivityForResult(intent2, 1002);

                }else {
                    ARouter.getInstance().build("/function/mmmDetails").withInt("oid", mList.get(position).getOid()).withInt("type",2).navigation();
                }
            }
        });


        llEmpty = findViewById(R.id.ll_empty);
        llEmpty.setVisibility(View.GONE);
        swipeRefres = findViewById(R.id.swipe_refres);

        swipeRefres.setEnableRefresh(true);//是否启用下拉刷新功能
        swipeRefres.setEnableLoadMore(true);//是否启用上拉加载功能
        swipeRefres.setEnableAutoLoadMore(true);//是否启用列表惯性滑动到底部时自动加载更多
        swipeRefres.setRefreshHeader(new ClassicsHeader(this));
        swipeRefres.setRefreshFooter(new ClassicsFooter(this));

        swipeRefres.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                params = new HttpParams();
                page = 1;
                //initHttpData(false);
                selectListCondition(true);
            }
        });
        swipeRefres.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                page++;
                params = new HttpParams();
                //initHttpData(false);
                selectListCondition(true);
            }
        });


        params = new HttpParams();
        params.put("current", page);
        params.put("size", "10");
        initHttpData(true);

        cbType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupViewResultList(view,resultData,getResources().getString(R.string.sx_kblx));
            }
        });
        cbSort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupViewTypeList(view,typeData,getResources().getString(R.string.sx_zt));
            }
        });
    }
    /**
     *  @author ljp
     *  @time   14:11
     *  @describe 弹出筛选条件list()
     */
    private void showPopupViewResultList(View view, String[] data, final String value){
        if(popupViewResult==null){
            popupViewResult = (CustomPartShadowPopupView) new XPopup.Builder(activity)
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }
                        @Override
                        public void onDismiss() {
                            cbType.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(activity));
            popupViewResult.setStringData(data, null);
            popupViewResult .setCheckedPosition(resultPosition);
            popupViewResult .setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    resultPosition = position;
                    cbType.setText(position == 0 ?value:text);
                    page = 1;
                     selectListCondition(true);
                }
            });
        }
        popupViewResult.show();
    }
    /**
     *  @author ljp
     *  @time   14:46
     *  @describe 筛选条件查询
     */
    private void selectListCondition(boolean isFirst) {
        params.clear();
        params.put("current", String.valueOf(page));
        params.put("size", "10");
        String s = mEtDjbh.getText().toString();
        if(!TextUtils.isEmpty(s)) {
            if (resultPosition > 0) {
                if (typePosition > 0) {
                    params.put("type", resultPosition - 1);
                    params.put("state", typePosition - 1);
                    params.put("code", s);
                }else {
                    params.put("type", resultPosition - 1);
                    params.put("code", s);
                }
            }else {
                if (typePosition > 0) {
                    params.put("state", typePosition - 1);
                }
            }
        }else {
            if (resultPosition > 0) {
                if (typePosition > 0) {
                    params.put("type", resultPosition - 1);
                    params.put("state", typePosition - 1);
                }else {
                    params.put("type", resultPosition - 1);
                }
            }else {
                if (typePosition > 0) {
                    params.put("state", typePosition - 1);
                }
            }

        }
        initHttpData(isFirst);
    }

    /**
     *  @author ljp
     *  @time   14:11
     *  @describe 弹出筛选条件list()
     */
    private void showPopupViewTypeList(View view,String[] data,final String value){
        if(popupViewType==null){
            popupViewType = (CustomPartShadowPopupView) new XPopup.Builder(activity)
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }
                        @Override
                        public void onDismiss() {
                            cbSort.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(activity));
            popupViewType.setStringData(data, null);
            popupViewType .setCheckedPosition(typePosition );
            popupViewType .setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    typePosition = position;
                    cbSort.setText(position == 0 ? value:text);
                    page = 1;
                    selectListCondition(true);
                }
            });
        }
        popupViewType.show();
    }
    @Override
    protected void initData() {

    }

    private void initHttpData(final boolean isFirst) {
        Log.e(TAG, "initHttpData: ----"+params.toString());
        OkGoUtils.getInstance().post(this, URL.GET_KANBAN, params, 1, false, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (response.getCode() == 200) {
                    String data = response.getDataInfo().toString();
                    LogUtils.e("data======" + data);
                    swipeRefres.finishLoadMore();
                    if (!isFirst)
                        swipeRefres.finishRefresh();

                    List<MMMBean> mmmBeans = JSON.parseArray(data, MMMBean.class);

                    if (page != 1) {
                        if (mmmBeans == null || mmmBeans.size() == 0) {
                            swipeRefres.finishLoadMoreWithNoMoreData();

                        }
                    } else {
                        mList.clear();
                        if (mmmBeans.size() == 0) {
                            llEmpty.setVisibility(View.VISIBLE);
                        } else {
                            llEmpty.setVisibility(View.GONE);
                        }

                    }
                    for (MMMBean bean : mmmBeans) {
                        mList.add(bean);
                    }
                    mAdapter.replaceData(mList);

                } else {
                    showToast(response.getMsg());
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_or_code) {
            Intent intent = new Intent(MMMActivity.this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        }

    }
    public void onClickQuery(View view) {
       // final String s = mEtDjbh.getText().toString();
        params.put("current", "1");
        params.put("size", "10");
       // params.put("code", s);
        //initHttpData(true);
        selectListCondition(true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    final String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEtDjbh.setText(result);
                    params = new HttpParams();
                   // params.put("code", result);
                   // initHttpData(true);
                    selectListCondition(true);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                }
            }
        } else if (1002 == requestCode && 0 != resultCode){
            params.put("current", "1");
            params.put("size", "10");
            //initHttpData(true);
            selectListCondition(true);
        }
    }
}
